package com.imooc.mall.filter;


import com.imooc.mall.common.ApiRestResponse;
import com.imooc.mall.common.Constant;
import com.imooc.mall.exception.ImoocMallExceptionEnum;
import com.imooc.mall.model.pojo.Category;
import com.imooc.mall.model.pojo.User;
import com.imooc.mall.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author yijiu
 * @version 1.0
 * @description: TODO
 * @date 2022/2/28 12:34
 */
//选择javax.servlet.Filter
/**
 * @description: 管理员校验过滤器
 */
public class AdminFilter implements Filter {

    @Autowired
    UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //从request中获取session
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute(Constant.IMOOC_MALL_USER);
        if (currentUser == null) {
//            return ApiRestResponse.error(ImoocMallExceptionEnum.NEED_LOGIN);
            //设置编码类型解决，请求返回的json类型为字符串乱码
            servletResponse.setCharacterEncoding("UTF-8");
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            out.write("{\n" +
                    "    \"status\": 1007,\n" +
                    "    \"msg\": NEED_LOGIN,\n" +
                    "    \"data\": null,\n" +
                    "}");
            out.flush();
            out.close();
            return;
        }
        //校验是否是管理员
        if (userService.checkAdminRole(currentUser)) {
            //是管理员，执行操作   通过过滤
           filterChain.doFilter(servletRequest,servletResponse);
        } else {
            servletResponse.setCharacterEncoding("UTF-8");  //为了解决返回字符乱码问题，不过这里不加也可以
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            out.write("{\n" +
                    "    \"status\": 1009,\n" +
                    "    \"msg\": NEED_LOGIN,\n" +
                    "    \"data\": null,\n" +
                    "}");
            out.flush();
            out.close();
        }
    }

    @Override
    public void destroy() {

    }
}
